#!/usr/bin/env node

const { getAccessToken, urlOf, jsonOfResponse } = require('./index.js')
const https = require('https')

function listRepos( owner = "", is_org = false, page = 1, per_page = 20 ) {
    console.debug( "listRepos:" )

    var url = urlOf( owner, is_org ) + "/repos" + '?access_token=' + getAccessToken() + "&page=" + page + "&per_page=" + per_page
    //per_page=20 by default, can be omited 
    var total_count = 0

    //https://gitee.com/api/v5/user/repos
    console.log( "url: " + url )

    const req = https.get( url, ( res ) => {
        console.log( 'response: ', res.statusCode )
        var total_count = parseInt(res.headers['total_count'])
        var total_page = parseInt(res.headers['total_page'])
        console.log( 'response total_page: ' + total_page )
        console.log( 'response total_count: ' + total_count )
        var size = res.headers[ 'content-length' ]
        jsonOfResponse(res, (json) => {
            for ( var i = 0; i <= json.length - 1; i++ ) {
                console.log( "[" + ( i + (per_page * page - per_page) + 1 ) + "] url: https://gitee.com/" + json[ i ].full_name + " " + ( json[ i ].private ? ", private" : ", public" ), ( json[ i ].fork ? ( ", forked from: " + json[ i ].parent.url ) : "" ) )
            }

            console.log( "curr: " + ( per_page * page ) )
            if (per_page * page < total_count) {
                console.log("should load next page.")
                listRepos(owner, is_org, page + 1, per_page)
            }

        })
    } ).on( "error", ( error ) => {
        console.log( "error: " + error )
    } ).on('end', () => {
        console.log("end")
        //listRepos(owner, is_org, page + 1)
    })
}

function readConfig(argv) {
    if (argv.length < 3) return { type: "user" }
    return { type: "orgs", name: argv[2] }
}

let config = readConfig(process.argv)

if (config.type == 'user') {
    listRepos("", false, 1)
} else if (config.type == 'orgs') {
    listRepos(config.name, true, 1)
}